package de.hijacksoft.isledesktopsync.adapter;

import de.hijacksoft.isle.classes.Item;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class DBAdapter {
    
    public void storeDB(ArrayList<Item> items, String filename) {
        try {
            
            // String filename = System.currentTimeMillis() + ".db";
            // String filename = "items.db";
            
            new File("./database/").mkdir();
            File saveFile = new File(filename);
            if(!saveFile.exists()) saveFile.createNewFile();
            else{
                // sync disabled because it didnt work
                // items = synchronizeDB(items, readDBFromFile(saveFile));
                saveFile.delete();
                saveFile.createNewFile();
            }

            // write to new file
            FileWriter fstream = new FileWriter(filename);
            BufferedWriter out = new BufferedWriter(fstream);
            
            if(items != null){
                for(Item item : items) if(item != null) out.write(item.toString() + "\n");
            }
            else System.err.println("Failed storing the db... " + "NullPointerException");
            
            out.close();
        } catch (IOException ex) {
            System.err.println("Failed storing the db... ");
            ex.printStackTrace();
        }

    }
    
    public ArrayList<Item> readDBFromFile(File file){

        ArrayList<Item> items = new ArrayList<Item>();

        try {
            if(file.exists()) {
            
            BufferedReader in = new BufferedReader(new FileReader(file.getAbsolutePath()));
            String line;
            
            while ((line = in.readLine()) != null) {

                Item addItem = Item.getItemFromString(line);
                if(addItem != null) items.add(addItem);
                            
            }
                in.close();
            }
            else return null;
        } catch (IOException ex) {
            System.out.println("Failed reading the db: " + ex.toString());
        }
        
        return items;
        
    }
    
    public ArrayList<Item> readDBFromFile(String filename){
        return readDBFromFile(new File(filename));
    }
      
    /**
     * Synchronizes two Item Databases preferring the newer Database as data source
     * @param newerDB the newer Database
     * @param olderDB the older Database
     * @return 
     */
    
    public ArrayList<Item> synchronizeDB(ArrayList<Item> newerDB, ArrayList<Item> olderDB){
        ArrayList<Item> syncDB = new ArrayList<Item>();

        for(Item newItem : newerDB){
            
            boolean found = false;
            
            for(Item oldItem : olderDB){
                
                if(newItem.barcode == oldItem.barcode || newItem.name == oldItem.name){
                    found = true;
                    
                    Item combItem = oldItem;
                    if(newItem.amount != oldItem.amount) combItem.amount = newItem.amount;
                    if(newItem.name != oldItem.name) combItem.name = newItem.name;
                    if(newItem.barcode != oldItem.barcode) combItem.barcode = newItem.barcode;
                    if(newItem.price != oldItem.price) combItem.price = newItem.price;
                    if(newItem.id != oldItem.id) combItem.id = newItem.id;
                    if(newItem.lastbought != oldItem.lastbought) combItem.lastbought = newItem.lastbought;
                    if(newItem.avgperiod != oldItem.avgperiod) combItem.avgperiod = newItem.avgperiod;
                    if(newItem.category.id != oldItem.category.id) combItem.category.id = newItem.category.id;
                    if(newItem.boughtcount != oldItem.boughtcount) combItem.boughtcount = newItem.boughtcount;
                    
                    syncDB.add(combItem);
                }
                
            }
            
            if(!found) syncDB.add(newItem);
            
        }
        
        for(Item oldItem : olderDB){
            
            boolean found = false;
            
            for(Item newItem : newerDB){
                
                if(newItem.barcode == oldItem.barcode || newItem.name == oldItem.name){
                    found = true;
                }
                
            }
            
            if(!found) syncDB.add(oldItem);
            
        }
        
        return syncDB;
        
    }
    
}
